﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProDivingAdmin2salmon14
{
    public partial class JudgeForm : Form, IJudgeForm
    {
        private bool isEdit = false;
        public JudgeForm()
        {
            InitializeComponent();

            this.VisibleChanged += JudgeForm_VisibleChanged;

            this.dataGridViewJudge.Columns.Add("ID", "ID");
            this.dataGridViewJudge.Columns.Add("fullName", "Name");
            this.dataGridViewJudge.Columns.Add("nationality", "Nationality");
            this.dataGridViewJudge.RowHeadersVisible = false;

            this.dataGridViewJudge.Columns["ID"].ReadOnly = true;
            this.dataGridViewJudge.Columns["ID"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.dataGridViewJudge.Columns["fullName"].ReadOnly = true;
            this.dataGridViewJudge.Columns["fullName"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.dataGridViewJudge.Columns["nationality"].ReadOnly = true;
            this.dataGridViewJudge.Columns["nationality"].SortMode = DataGridViewColumnSortMode.NotSortable;
            this.dataGridViewJudge.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            this.dataGridViewJudge.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dataGridViewJudge.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridViewJudge.MultiSelect = false;
            this.dataGridViewJudge.AllowUserToAddRows = false;

            this.dataGridViewJudge.CellEndEdit += dataGridViewJudge_CellEndEdit;
        }

        void dataGridViewJudge_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (!this.isEdit)
                {
                    this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex].ReadOnly = true;
                    if (this.dataGridViewJudge.CurrentCell.ColumnIndex + 1 <= 2)
                    {
                        if (this.dataGridViewJudge.CurrentCell.ColumnIndex == 0)
                        {
                            if (Regex.Matches(this.dataGridViewJudge.CurrentCell.Value.ToString(), @"[a-zA-Z]").Count > 0)
                            {
                                this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex].ReadOnly = false;
                                this.dataGridViewJudge.CurrentCell.Selected = true;
                                this.dataGridViewJudge.BeginEdit(true);
                                return;
                            }
                            else if (this.dataGridViewJudge.CurrentCell.Value.ToString().Length > 2 || this.dataGridViewJudge.CurrentCell.Value.ToString().Length < 1)
                            {
                                this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex].ReadOnly = false;
                                this.dataGridViewJudge.CurrentCell.Selected = true;
                                this.dataGridViewJudge.BeginEdit(true);
                                return;
                            }
                            else if (GetIdList().Contains(this.dataGridViewJudge.CurrentCell.Value.ToString()))
                            {
                                MessageBox.Show("Chosen ID Already exists, please choose a unique id between 0 and 99", "Duplicate ID");
                                this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex].ReadOnly = false;
                                this.dataGridViewJudge.CurrentCell.Selected = true;
                                this.dataGridViewJudge.BeginEdit(true);
                                return;
                            }
                        }
                        try
                        {
                            this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex + 1].ReadOnly = false;
                            this.dataGridViewJudge.CurrentRow.Cells[this.dataGridViewJudge.CurrentCell.ColumnIndex + 1].Selected = true;
                            this.dataGridViewJudge.BeginEdit(true);
                        }
                        catch (InvalidOperationException)
                        {
                            return;
                        }
                    }
                    else
                    {
                        if(EventAddJudgeToList != null && !this.isEdit)
                        {
                            if (EventGetAmountOfJudges != null)
                            {
                                if (this.dataGridViewJudge.Rows.Count <= EventGetAmountOfJudges())
                                {
                                    EventAddJudgeToList(new Judge(this.dataGridViewJudge.CurrentRow.Cells["fullName"].Value.ToString(), this.dataGridViewJudge.CurrentRow.Cells["nationality"].Value.ToString(), Int32.Parse(this.dataGridViewJudge.CurrentRow.Cells["ID"].Value.ToString())));
                                    if (this.dataGridViewJudge.Rows.Count == EventGetAmountOfJudges())
                                    {
                                        this.buttonAdd.Enabled = false;
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("To many judges", "Error");
                                    this.dataGridViewJudge.Rows.Remove(this.dataGridViewJudge.Rows[this.dataGridViewJudge.Rows.Count - 1]);
                                }
                            }
                        }
                    }

                }//if(!this.isEdit)
                else if (EventEditJudge != null && this.isEdit)
                {
                    EventEditJudge(this.dataGridViewJudge.CurrentRow.Index, new Judge(this.dataGridViewJudge.CurrentRow.Cells["fullName"].Value.ToString(), this.dataGridViewJudge.CurrentRow.Cells["nationality"].Value.ToString(), Int32.Parse(this.dataGridViewJudge.CurrentRow.Cells["ID"].Value.ToString())));
                    this.isEdit = false;
                }
            }
            catch
            {
                
            }
        }

        void JudgeForm_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                if (EventGetAmountOfJudges() == 0)
                {
                    bool done = false;
                    while (!done)
                    {
                        string result = Microsoft.VisualBasic.Interaction.InputBox("How many judges do you want in the contest", "Amount of Judges", "7");
                        if (EventSetAmountOfJudges != null && Regex.Matches(result, @"[3,5,7,9]").Count == 1)
                        {
                            EventSetAmountOfJudges(Int32.Parse(result));
                            done = true;
                        }
                        else
                        {
                            MessageBox.Show("Invalid amount. Only 3,5,7,9 is valid amounts", "Invalid amount");
                        }
                    }
                }
                if (EventGetAmountOfJudges() > this.dataGridViewJudge.Rows.Count)
                {
                    this.buttonAdd.Enabled = true;
                }
                if (EventGetJudgeList != null)
                {
                    this.dataGridViewJudge.Rows.Clear();
                    foreach (var judge in EventGetJudgeList())
                    {
                        this.dataGridViewJudge.Rows.Add(new DataGridViewRow());
                        this.dataGridViewJudge.Rows[this.dataGridViewJudge.Rows.Count - 1].Cells["ID"].Value = judge.ID;
                        this.dataGridViewJudge.Rows[this.dataGridViewJudge.Rows.Count - 1].Cells["fullName"].Value = judge.fullName;
                        this.dataGridViewJudge.Rows[this.dataGridViewJudge.Rows.Count - 1].Cells["nationality"].Value = judge.nationality;
                    }
                } 
            }
        }

        public event DelegateGetJudgeList EventGetJudgeList = null;
        public event DelegateAddJudgeToList EventAddJudgeToList = null;
        public event DelegateGetAmountOfJudges EventGetAmountOfJudges = null;
        public event DelegateDeleteJudgeFromList EventDeleteJudgeFromList = null;
        public event DelegateEditJudge EventEditJudge = null;
        public event DelegateSetAmountOfJudges EventSetAmountOfJudges = null;
        public event DelegateSaveJudges EventSaveJudges = null;
        public event DelegateReorderJudgeList EventReorderJudgeList = null;

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            this.dataGridViewJudge.Rows.Add(new DataGridViewRow());
            this.dataGridViewJudge.Rows[this.dataGridViewJudge.Rows.Count - 1].Cells["ID"].Selected = true;
            this.dataGridViewJudge.CurrentCell.ReadOnly = false;
            this.dataGridViewJudge.BeginEdit(true);
            if (EventGetAmountOfJudges != null)
            {
                if (EventGetAmountOfJudges() == this.dataGridViewJudge.Rows.Count) 
                {
                    this.buttonAdd.Enabled = false;
        }
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure?", "Really?", MessageBoxButtons.YesNo);


            if (EventDeleteJudgeFromList != null && result == DialogResult.Yes)
            {
                try
                {
                EventDeleteJudgeFromList(Int32.Parse(this.dataGridViewJudge.CurrentRow.Cells["ID"].Value.ToString()));
                }
                catch (NullReferenceException ex)
                {
                    System.Console.WriteLine("Judge Add eddit: " + ex.Message);
                }
                try
                {
                this.dataGridViewJudge.Rows.Remove(this.dataGridViewJudge.CurrentRow);
                }
                catch (ArgumentNullException exn) 
                {
                    System.Console.WriteLine("Judge Add Eddit: Can't remove something that doesn't excist!");
                }
                if (EventGetAmountOfJudges != null)
                {
                    if (this.dataGridViewJudge.Rows.Count < EventGetAmountOfJudges())
                    {
                        this.buttonAdd.Enabled = true;
                    }
                }

                EventReorderJudgeList();
            }
        }

        private List<string> GetIdList()
        {
            List<string> returnList = new List<string>();
            foreach (DataGridViewRow row in this.dataGridViewJudge.Rows)
            {
                if (row.Index != this.dataGridViewJudge.Rows.Count - 1)
                {
                    returnList.Add(row.Cells["ID"].Value.ToString());
                }
            }
            return returnList;
        }

        private void buttonEdit_Click(object sender, EventArgs e)
        {
            try
            {
                this.dataGridViewJudge.CurrentCell.ReadOnly = false;
                this.dataGridViewJudge.BeginEdit(true);
                this.isEdit = true;
            }
            catch (NullReferenceException)
            {
                System.Console.WriteLine("Can't edit a row that does not exist");
            }
        }

        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {

            List<Judge> judgeList = new List<Judge>();
            foreach (DataGridViewRow row in this.dataGridViewJudge.Rows)
            {
                judgeList.Add(new Judge(row.Cells["fullName"].Value.ToString(), row.Cells["nationality"].Value.ToString(), Int32.Parse(row.Cells["ID"].Value.ToString())));
            }

            if (EventGetAmountOfJudges != null)
            {
                if (judgeList.Count == EventGetAmountOfJudges())
                {
                    SaveFileDialog saveFile = new SaveFileDialog();
                    saveFile.Filter = "Judge Files (*.ju)|*.ju";

                    DialogResult result = saveFile.ShowDialog(this);

                    if (result == DialogResult.OK)
                    {
                        string filePath = saveFile.FileName;
                        if (EventSaveJudges != null)
                        {
                            EventSaveJudges(filePath, judgeList);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Wrong amount of judges, amount must be " + EventGetAmountOfJudges().ToString(), "Wrong amount of judges");
                }
            }


        }

        private void JudgeForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (EventSetAmountOfJudges != null)
            {
                EventSetAmountOfJudges(0);
            }
        }


        
    }
}
